/* 备份数据,不影响原数据 */
let dataBackup = arr

/* 变量设置 */
let sum = 0,
	num = 0

/* 获取DOM元素 */
const list = document.querySelector(".xtx-cart-page .container .cart table tbody")
const total = document.querySelector(".xtx-cart-page .container .action .total")

/* 初始渲染 */
render()

/* 删除事件 */
function deleteEvent() {
	document.querySelectorAll("#deleteBtn").forEach(item => {
		item.addEventListener("click", function () {
			dataBackup.forEach((item, index) => {
				if (item.id == this.dataset.id) {
					const tr = document.querySelector(`#id${item.id}`)
					tr.style.transform = `translateX(500px)`
					tr.style.opacity = `0`
					tr.style.height = `0px`
					// tr.style.display = `none`
					setTimeout(() => {
						dataBackup.splice(index, 1)
						render()
					}, 300)
					return
				}
			})
		})
	})
}

/* 渲染 */
function render() {
	renderList()
	renderFooter()
}

/* 列表渲染 */
function renderList() {
	;(sum = 0), (num = 0)
	list.innerHTML = dataBackup
		.map((item, index) => {
			const { id, attrsText, name, price, picture, count } = item
			sum += price * count
			num += count
			return `
            <tr class="listTr" id="id${id}">
                <td>${index + 1}</td>
                <td>
					<img src=${picture} alt="">
					<div>
						<h4>${name}</h4>
						<p>${attrsText}</p>
					</div>
				</td>
                <td>${price}</td>
                <td>${count}</td>
                <td style="color:red;">${price * count}</td>
                <td>
                    <a id="deleteBtn" data-id=${id} style="color:green;" href="javascript:;">删除</a>
                </td>
            </tr>
            `
		})
		.join("")
	deleteEvent()
}

/* 底部渲染 */
function renderFooter() {
	total.innerHTML = `共 ${num} 件商品，商品合计：<span class="red">¥${sum}</span>`
}
